package com.wx.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.wx.core.service.CoreService;
import com.wx.core.service.MenuService;
import com.wx.message.resq.Article;
import com.wx.message.resq.NewsMessage;
import com.wx.message.resq.TextMessage;
import com.wx.util.MessageUtil;

import dwz.persistence.beans.WechatArticle;
import dwz.persistence.beans.WechatMenu;
import dwz.persistence.mapper.WechatArticleMapper;
import dwz.persistence.mapper.WechatMenuMapper;

/**
 * 核心服务类
 * 
 * @author liaoxj
 * @date 2014-07-07
 */
@Service("coreService")
public class CoreServiceImpl implements CoreService {
	@Resource
	private WechatMenuMapper menuMapper;
	@Resource
	private WechatArticleMapper articeMapper;
	@Resource
	private MenuService menuService;
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");

			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);
	        // 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义  
			textMessage.setContent("欢迎访问<a href=\"www.baidu.com\">百姓大药房</a>!");  
			// 将文本消息对象转换成xml字符串  
			respMessage = MessageUtil.textMessageToXml(textMessage);  


			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				respContent = "您发送的是文本消息！";
				
		          // 接收用户发送的文本消息内容  
				String content = requestMap.get("Content");  
				// 创建图文消息  
				NewsMessage newsMessage = new NewsMessage();  
				newsMessage.setToUserName(fromUserName);  
				newsMessage.setFromUserName(toUserName);  
				newsMessage.setCreateTime(new Date().getTime());  
				newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
				newsMessage.setFuncFlag(0);  
				
				List<Article> articleList = new ArrayList<Article>();  
				// 单图文消息  
				if ("1".equals(content)) {  
					Article article = new Article();
					
					WechatArticle waricle=articeMapper.load(3);
					article.setTitle(waricle.getTitle());  
					article.setDescription(waricle.getTitle());  
					article.setPicUrl(waricle.getPicUrl());  
					article.setUrl(waricle.getUrl());  
					article.setDescription(waricle.getDescription());
					articleList.add(article);  
					// 设置图文消息个数  
					newsMessage.setArticleCount(articleList.size());  
					// 设置图文消息包含的图文集合  
					newsMessage.setArticles(articleList);  
					// 将图文消息对象转换成xml字符串  
					respMessage = MessageUtil.newsMessageToXml(newsMessage);  
				}else if("2".equals(content)){
					//发送图片连接消息					
					Article article1 = new Article();
					article1.setTitle("西曼色彩时尚教育联想方式和地址");
					article1.setDescription("");
					// 将图片置为空
					article1.setPicUrl("http://mms2.fzl3g.com/upload/20120622/2012062212052819.jpg");
					article1.setUrl("http://my.oschina.net/ukapollo");

					Article article2 = new Article();
					article2.setTitle("西曼色彩时尚教育联想方式和地址");
					article2.setDescription("");
					article2.setPicUrl("http://avatar.csdn.net/1/4/A/1_lyq8479.jpg");
					article2.setUrl("http://blog.csdn.net/lyq8479/article/details/8949088");

					Article article3 = new Article();
					article3.setTitle("西曼色彩时尚教育联想方式和地址");
					article3.setDescription("");
					article3.setPicUrl("http://avatar.csdn.net/1/4/A/1_lyq8479.jpg");
					article3.setUrl("http://blog.csdn.net/lyq8479/article/details/8952173");

					articleList.add(article1);
					articleList.add(article2);
					articleList.add(article3);
					newsMessage.setArticleCount(articleList.size());
					newsMessage.setArticles(articleList);
					respMessage = MessageUtil.newsMessageToXml(newsMessage); 
				}else if("3".equals(content)){
					//发送图片连接消息					
					Article article1 = new Article();
					article1.setTitle("西曼教育简介");
					article1.setDescription("");
					// 将图片置为空
					article1.setPicUrl("http://apollo2099.sinaapp.com/res/images/m_1303967870670.jpg");
					article1.setUrl("http://my.oschina.net/ukapollo");

					Article article2 = new Article();
					article2.setTitle("私人形象顾问课程");
					article2.setDescription("");
					article2.setPicUrl("http://apollo2099.sinaapp.com/res/images/1313473186634.jpg");
					article2.setUrl("http://my.oschina.net/ukapollo");

					Article article3 = new Article();
					article3.setTitle("服装陈列师课程");
					article3.setDescription("");
					article3.setPicUrl("http://apollo2099.sinaapp.com/res/images/m_1341534303744.jpg");
					article3.setUrl("http://my.oschina.net/ukapollo");
					
					Article article4 = new Article();
					article4.setTitle("软装设计顾问课程");
					article4.setDescription("");
					article4.setPicUrl("http://apollo2099.sinaapp.com/res/images/m_1303967870670.jpg");
					article4.setUrl("http://my.oschina.net/ukapollo");
					
					
					Article article5 = new Article();
					article5.setTitle("色彩心里师课程");
					article5.setDescription("");
					article5.setPicUrl("http://apollo2099.sinaapp.com/res/images/m_1303967870670.jpg");
					article5.setUrl("http://my.oschina.net/ukapollo");
					
					Article article6 = new Article();
					article6.setTitle("色彩搭配师课程");
					article6.setDescription("");
					article6.setPicUrl("http://apollo2099.sinaapp.com/res/images/m_1303967870670.jpg");
					article6.setUrl("http://my.oschina.net/ukapollo");

					articleList.add(article1);
					articleList.add(article2);
					articleList.add(article3);
					articleList.add(article4);
					articleList.add(article5);
					articleList.add(article6);
					newsMessage.setArticleCount(articleList.size());
					newsMessage.setArticles(articleList);
					respMessage = MessageUtil.newsMessageToXml(newsMessage); 
				}else if("4".equals(content)){
					WechatMenu wmenu=menuMapper.getMenuByKeyName("V3001_INFO");
					if(wmenu!=null&&wmenu.getCode()!=null){
						List<WechatArticle> alist=articeMapper.findByMenuCode(wmenu.getCode());
						if(alist!=null){
							for (int i = 0; i < alist.size(); i++) {
								WechatArticle  warticle=alist.get(i);
								Article article = new Article();  
								article.setTitle(warticle.getTitle());  
								article.setDescription(warticle.getDescription());  
								article.setPicUrl(warticle.getPicUrl());  
								article.setUrl(warticle.getUrl());  
								articleList.add(article);  
							}
							// 设置图文消息个数  
							newsMessage.setArticleCount(articleList.size());  
							// 设置图文消息包含的图文集合  
							newsMessage.setArticles(articleList);  
							// 将图文消息对象转换成xml字符串  
							respMessage = MessageUtil.newsMessageToXml(newsMessage);  
						}
					}
				}else if("5".equals(content)){
					Integer result=menuService.createMenu("wx7240c5aaa704d14e", "f032b3442106bd0ee2879837de92883f");
					System.out.println("创建菜单"+result);
				}else if("6".equals(content)){
					Integer result=menuService.deleteMenu("wx7240c5aaa704d14e", "f032b3442106bd0ee2879837de92883f");
					System.out.println("删除菜单"+result);
				}  
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！";
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！";
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "谢谢您的关注！";
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					List<Article> articleList = new ArrayList<Article>();
					// 创建图文消息
					NewsMessage newsMessage = new NewsMessage();
					newsMessage.setToUserName(fromUserName);
					newsMessage.setFromUserName(toUserName);
					newsMessage.setCreateTime(new Date().getTime());
					newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
					newsMessage.setFuncFlag(0);
					
					// TODO 自定义菜单权没有开放，暂不处理该类消息
					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");
					//根据菜单事件查询菜单信息，再根据菜单查询菜单对应的文章信息
					WechatMenu wmenu=menuMapper.getMenuByKeyName(eventKey);
					if(wmenu!=null&&wmenu.getCode()!=null){
						List<WechatArticle> alist=articeMapper.findByMenuCode(wmenu.getCode());
						if(alist!=null){
							for (int i = 0; i < alist.size(); i++) {
								WechatArticle  warticle=alist.get(i);
								Article article = new Article();  
								article.setTitle(warticle.getTitle());  
								article.setDescription(warticle.getDescription());  
								article.setPicUrl(warticle.getPicUrl());  
								article.setUrl(warticle.getUrl());  
								articleList.add(article);  
							}
							// 设置图文消息个数  
							newsMessage.setArticleCount(articleList.size());  
							// 设置图文消息包含的图文集合  
							newsMessage.setArticles(articleList);  
							// 将图文消息对象转换成xml字符串  
							respMessage = MessageUtil.newsMessageToXml(newsMessage);  
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}
}

